<template>
  <div class="app-container">
    <el-form :model="form" ref="form" size="mini" :inline="true" label-width="68px">
      <el-row v-if="form.restbreakId">
        <el-descriptions :column="3" border>
          <el-descriptions-item label="项目区域"><dict-tag :options="dict.type.cld_project_region"
              :value="form.projectRegion" /></el-descriptions-item>
          <el-descriptions-item label="项目名称"> {{ form.projectName }}</el-descriptions-item>
          <el-descriptions-item label="排休月份">{{ form.restbreakYear + '-' + form.restbreakMonth }}</el-descriptions-item>
        </el-descriptions>
      </el-row>
      <el-row v-else>
        <el-form-item label="项目区域" prop="projectRegion">
          <el-select v-model="form.projectRegion" placeholder="请选择" @change="handleRegionChange">
            <el-option v-for="dict in dict.type.cld_project_region" :key="dict.value" :label="dict.label"
              :value="parseInt(dict.value)"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="项目名称" prop="projectName">
          <el-select v-model="form.projectId" placeholder="请选择" @change="handleProjectChange">
            <el-option v-for="item in projectOptions" :key="item.projectId" :label="item.projectName"
              :value="item.projectId"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="排休月份" prop="projectAccountId">
          <el-date-picker v-model="form.month" type="month" placeholder="选择月" :picker-options="pickerOptions"
            @change="handleMonthChange">
          </el-date-picker>
        </el-form-item>
      </el-row>


      <el-row :gutter="20">
        <!--小组岗位-->
        <el-col :span="3" :xs="24">
          <div class="head-container">
            <el-tree :data="groupJobOptions" :props="defaultProps" :expand-on-click-node="false" ref="tree"
              node-key="id" default-expand-all highlight-current @node-click="handleNodeClick">
              <span class="custom-tree-node" slot-scope="{ node, data }">
                <span>{{ node.label }}
                  <span v-if="data.staffId">- {{ data.postName }}({{ data.count ? data.count : 0
                    }})</span>
                </span>
              </span>
            </el-tree>
          </div>
        </el-col>
        <!--日历数据-->
        <el-col :span="21" :xs="24">
          <el-calendar :value="form.month">
            <!-- 这里使用的是 2.5 slot 语法，对于新项目请使用 2.6 slot 语法-->
            <template slot="dateCell" slot-scope="{date, data}">
              <div style="height: 100%;" v-for="(item, index) in form.calendarList" :key="item.calendarId"
                v-if="item.calendayDate == data.day && data.type == 'current-month'"
                :class="{ 'is-scheduling': !item.isScheduling }" @click="handleWorkInfo(item, index)">
                <el-row>
                  <el-col :span="20"
                    v-if="item.calendarYear == new Date().getFullYear() && item.calendayMonth == new Date().getMonth() + 1 && item.calendayDay == new Date().getDate()">
                    今天
                  </el-col>
                  <el-col :span="20" v-else>
                    {{ item.calendayDay }}
                  </el-col>
                  <el-col :span="4">
                    <div class="holidays" v-if="item.calendayType == 2">
                      <p>{{ item.calendayTypeDes }}</p>
                    </div>
                  </el-col>
                </el-row>
                <el-row v-if="item.staffList" :gutter="20">
                  <el-col :span="12" v-for="(staff, staffIndex) in item.staffList"
                    :key="staff.restbreaksCalendarMemberId">
                    <el-tag v-if="staff.projectStaffId" size="mini"
                      @click.stop="handleDeleteStaff(staff, index, staffIndex)">
                      {{ staff.groupNames ?  staff.groupNames : '离岗' }}</br>{{ staff.staffName }}
                    </el-tag>
                  </el-col>
                </el-row>
                <div class="no-work-class">
                  <div class="tips-class" v-if="!item.isScheduling">
                    休息
                  </div>
                </div>
              </div>
            </template>
          </el-calendar>
        </el-col>
      </el-row>
      <div class="dialog-footer-options" v-if="!form.restbreakId">
        <el-button type="primary" @click="submitForm">保存</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-form>
  </div>
</template>

<script>
import { selectGroupStaffByProjectId } from '@/api/cld/publicCommon'
import { getList } from '@/api/cld/project'
import { selectHolidays } from '@/api/cld/publicCommon'
import { getProjectSet } from '@/api/cld/set'
import { addRestbreaks, updateRestbreaks, getRestbreaks } from '@/api/cld/restbreaks'
import { background } from "quill/ui/icons";
export default {
  name: "addScheduling",
  dicts: ['cld_project_region'],
  data() {
    return {
      // 表单
      form: {
        calendarList: []
      },
      // 排休设置表单
      addForm: {},
      // 小组人员
      groupJobOptions: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      // 排休弹框
      open: false,
      // 排休id
      restbreakId: null,
      // 项目列表
      projectOptions: [],
      pickerOptions: {
        disabledDate(time) {
          return time.getFullYear() !== new Date().getFullYear();
        }
      },
      // 节假日
      holidays: [],
      // 当前选择日期
      currDay: null,
      // 当前选择人员
      currStaff: null,
    };
  },
  created() {
    this.restbreakId = this.$route.params && this.$route.params.restbreakId;
    if (this.restbreakId && this.restbreakId != 0) {
      this.handleGetRestbreak();
    }
  },
  computed: {

  },
  mounted() {

  },
  methods: {
    // 查询当月排休配置
    handleGetRestbreak() {
      getRestbreaks(this.restbreakId).then(res => {
        this.form = res.data;
        this.form.month = this.form.restbreakYear + '-' + this.form.restbreakMonth
        this.handleIsScheduling();
        this.getGroupJobList(this.form.projectId);
      })
    },
    // 查询小组人员
    getGroupJobList(projectId) {
      selectGroupStaffByProjectId(projectId).then(res => {
        this.groupJobOptions = res.data;
        this.calculateNumberBreaks();
      })
    },
    // 计算人员排休次数
    calculateNumberBreaks() {
      this.groupJobOptions.forEach(i => {
        i.children?.forEach(staff => {
          let count = 0;
          this.form.calendarList.forEach(c => {
            count += c.staffList.filter(c => c.projectStaffId == staff.staffId).length;
          })
          staff.count = this.form.projectSet.allMonthlyDay - count;
        })
      })
    },
    // 排休月份选择
    handleMonthChange(e) {
      this.form.restbreakYear = this.parseTime(e, '{y}');
      this.form.restbreakMonth = this.parseTime(e, '{m}');
      this.form.platform = 1;
      this.handleSelectHolidays();
    },
    // 获取当月节假日
    handleSelectHolidays() {
      selectHolidays({
        calendarYear: this.form.restbreakYear,
        calendayMonth: this.form.restbreakMonth
      }).then(res => {
        this.form.calendarList = res.data;
        this.handleIsScheduling();
      })
    },
    // 项目区域选择
    handleRegionChange(e) {
      getList({
        projectRegion: e,
        projectStatus: 2
      }).then(res => {
        this.projectOptions = res.data;
      })
    },
    // 选择项目
    handleProjectChange(e) {
      this.form.projectId = e;
      // 查询项目配置
      this.handleSelectProjectSet();
      // 查询项目小组人员
      this.getGroupJobList(e);

    },
    // 查询项目配置
    handleSelectProjectSet() {
      getProjectSet(this.form.projectId).then(res => {
        this.form.projectSet = res.data;
      })
    },
    // 左侧人员选择
    handleNodeClick(e) {
      if (e.staffId) {
        this.currStaff = e;
      } else {
        this.currStaff = null;
      }
    },
    // 取消
    cancel() {
      const obj = { path: "/cloudManage/salary/restbreaks", name: "Restbreaks" };
      this.$tab.closeOpenPage(obj);
      this.$tab.refreshPage(obj);
    },
    // 判断是否为节假日
    isHoliday(date) {
      let data = this.form.calendarList.find(item => {
        return item.calendayDate == date;
      })
      return data;
    },
    // 新增编辑排休
    handleWorkInfo(data, index) {
      if (this.currStaff) {
        // 当日是否可排休
        if (data.isScheduling) {
          if (!data.staffList) {
            data.staffList = [];
          }
          // 当天是否已安排该人员休息
          let currDayStaff = data.staffList.find(i => { return i.projectStaffId == this.currStaff.staffId });
          if (currDayStaff) {
            return this.$message.error(`已安排[${currDayStaff.staffJob}]在${data.calendayDate}日休息,请勿重复排休！`);
          }
          // 每人月休息天数
          let count = 0;
          this.form.calendarList.forEach(item => {
            if (item.staffList) {
              count += item.staffList.filter(i => i.projectStaffId == this.currStaff.staffId).length;
            }
          })
          if (count >= this.form.projectSet.allMonthlyDay) {
            return this.$message.error(`每月最多休息${this.form.projectSet.allMonthlyDay}天！`);
          }
          // 不同小组不可设置同一天休息
          // if (data.staffList.length > 0 && data.staffList.filter(i => i.projectGroupId == this.currStaff.groupId).length == 0) {
          //   return this.$message.error(`同一天不可安排不同小组人员休息！`);
          // }
          // 判断当日休息人数是否已达标
          if (data.staffList.length >= this.form.projectSet.allDailyRest) {
            return this.$message.error(`${data.calendayDate}休息人数已达上限！`);
          }
          // 该人员休息次数+1
          if (this.currStaff.count) {
            this.currStaff.count += 1;
          } else {
            this.currStaff.count = 1;
          }
          data.staffList.push({
            projectGroupId: this.currStaff.groupId,
            projectPostId: this.currStaff.postId,
            projectStaffId: this.currStaff.staffId,
            groupNames: this.currStaff.groupName + '-' + this.currStaff.staffName,
            staffJob: this.currStaff.postName
          })
          this.form = {
            ...this.form
          }
        }
      }
    },
    // 保存排休人员
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: '数据正在提交中...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          });
          if (this.form.restbreakId != null) {
            updateRestbreaks(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              loading.close();
              this.cancel();
            });
          } else {
            addRestbreaks(this.form).then(response => {
              this.$modal.msgSuccess("操作成功");
              loading.close();
              this.cancel();
            }).catch(() => {
              loading.close();
            });
          }
        }
      });
    },
    // 删除已排休人员
    handleDeleteStaff(staff, calendarIndex, staffIndex) {
      staff = {}
      this.form.calendarList[calendarIndex].staffList.splice(staffIndex, 1)
      this.form = {
        ...this.form
      }
      this.calculateNumberBreaks();
      // this.$modal.confirm(`是否移除[${staff.staffName}]排休信息？`).then(function () {

      //   return delWelfare(walfareIds);
      // }).then(() => {
      //   this.getList();
      //   this.$modal.msgSuccess("删除成功");
      // }).catch(() => { });
    },
    // 是否可安排排休
    handleIsScheduling() {
      this.form.calendarList.forEach(item => {
        item.isScheduling = true;
        // 判断是否周六休 及双休
        if ((this.form.projectSet.isWeekendRest == 1 && item.weekDay == 6) || (this.form.projectSet.isWeekendRest == 3 && [6, 7].includes(item.weekDay))) {
          item.isScheduling = false;
        }
        // 判断是否周日休 及双休
        if ((this.form.projectSet.isWeekendRest == 2 && item.weekDay == 7) || (this.form.projectSet.isWeekendRest == 3 && [6, 7].includes(item.weekDay))) {
          item.isScheduling = false;
        }
        // 判断是否节假日休息
        if (this.form.projectSet.isHolidayRest == 1 && item.calendayType == 2) {
          item.isScheduling = false;
        }
      })
    }
  }
};

</script>
<style scoped>
::v-deep .el-calendar-table .el-calendar-day {
  position: relative;
  min-height: 160px;
}

::v-deep .el-calendar-day {
  padding: 0px;
}

::v-deep .el-col-20 {
  margin-top: 5px;
  margin-left: 10px;
}

.holidays {
  position: absolute;
  right: -0.03rem;
  top: -1.03rem;
  color: #eb3333;
}

.holidays p {
  font-size: 12px;
  line-height: 14px;
  padding: 1px 2px;
}

.no-work-class {
  text-align: center;
  color: #a0cba0;
  line-height: 100px;
  font-weight: bold;
}

.icon-class {
  font-size: 20px;
  margin-bottom: 20px;
}

.el-tag--mini {
  height: 50px;
  text-align: center;
  margin-top: 5px;
  margin-left: 10px;
  padding: 5px
}

.handle-class {
  flex: 1;
}

::v-deep .el-calendar__button-group {
  display: none;
}

/*::v-deep 深度选择器 修改class样式*/
::v-deep td.is-selected {
  background-color: #ffffff;
}

.is-scheduling {
  background: #f1fff3;
}

::v-deep td.is-today {
  font-weight: bold;
  background-color: #e8f4ff;
}

::v-deep .holidays {
  top: 0rem;
  right: 0.5rem;
  font-size: 13px;
}

::v-deep .prev {
  background: #f6f6f6;
}

::v-deep .next {
  background: #f6f6f6;
}

::v-deep .el-tag--mini {
  border-radius: 10px;
  box-shadow: 5px 5px 5px #aabbcb;
  margin-top: 10px;
}

::v-deep .el-col-12{
  width:30%;
}
</style>
